/*
 * @Description: 新增排序规则弹窗组件
 * @Author: Rfan
 * @Date: 2022-03-07 11:24:01
 * @LastEditTime: 2023-01-12 16:25:34
 */

import { useEffect, useState } from 'react';
import { Button, Form, Modal } from 'antd';
import { fetchMetadata } from '@/api/metadata';
import { useOpeningContext } from '../../contexts/OpeningContext';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import FormItem from './common/FormItem';
import type { FC } from 'react';
import type { ICommonDialog, ICoordinate } from '@/interfaces/global';
import type { IMetadata } from '@/interfaces/metadata';

interface AddDialogProps extends ICommonDialog {
  type: number;
}

// 初始化表单数据
const initFormData = {
  visible: 1
};

const AddDialog: FC<AddDialogProps> = (props) => {
  const { visible, type, onClose } = props;
  const { list, selectAT, selectLevel, addOpeningFunc } = useOpeningContext();
  const [form] = Form.useForm();

  // 元数据列表
  const [fieldList, setFieldList] = useState<IMetadata[]>([]);

  useEffect(() => {
    // 打开弹窗请求元数据
    if (visible) {
      const params = {
        metadataFieldType: QUERY_METADATA_ALL,
        coordinate: {
          atType: selectAT.atType,
          atCode: selectAT.atCode,
          level: selectLevel.level
        }
      };
      fetchMetadata(params).then((res) => {
        setFieldList(res.data);
      });
    }
  }, [visible]);

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  /**
   * @description: 新增开放字段方法
   * @param {any} values 表单数据
   */
  const onFinish = (values: any) => {
    const coordinate: ICoordinate = {
      atCode: selectAT.atCode,
      atType: selectAT.atType,
      level: selectLevel.level
    };
    const openFieldList = [
      {
        ...values,
        type,
        sortNo: list.length + 1
      }
    ];
    addOpeningFunc({ coordinate, openFieldList }, type).then(() => {
      onCancel();
    });
  };

  /**
   * @description: 关闭弹窗方法
   */
  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="新建开放字段"
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={submitFunc}>
          保存
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        preserve={false}
        form={form}
        initialValues={initFormData}
        onFinish={onFinish}
      >
        <FormItem fieldList={fieldList} />
      </Form>
    </Modal>
  );
};

export default AddDialog;
